<template>
  <div class="thermostatVersions">
    <div class="header">
      <el-form
        :inline="true"
        :model="formInline"
        size="small"
        label-width="70px"
      >
        <el-form-item label="版本号">
          <el-select
            v-model="formInline.version"
            placeholder="请选择温控器版本"
            @change="onChange($event, 'version')"
            filterable
            clearable
          >
            <el-option
              v-for="item in versionList"
              :key="item.id"
              :label="item.versionNumber"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select
            v-model="formInline.type"
            placeholder="请选择设备类型"
            @change="onChange($event, 'type')"
            filterable
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号">
          <el-select
            v-model="formInline.unit"
            placeholder="请选择设备型号"
            @change="onChange($event, 'unit')"
            filterable
            clearable
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="add"
            >添加版本号</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <el-table
        class="table"
        ref="table"
        :data="tableData"
        row-key="id"
        :header-cell-style="{
          width: '100%',
          background: '#FAFAFA',
          color: '#606266',
          height: '60px'
        }"
        border
      >
        <el-table-column
          label="序号"
          prop="no"
          width="100"
          align="center"
          :show-overflow-tooltip="tooltip"
        ></el-table-column>
        <el-table-column
          label="版本号"
          prop="versionNumber"
          align="center"
          :show-overflow-tooltip="tooltip"
          min-width="150"
        >
          <template slot-scope="scoped">
            <div>
              <span v-if="scoped.row.versionNumber == null" style="color: red"
                >暂无数据</span
              >
              <span v-else>{{ scoped.row.versionNumber }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="适用设备类型"
          prop="type_name"
          min-width="150"
          :show-overflow-tooltip="tooltip"
          align="center"
        >
          <template slot-scope="scoped">
            <div>
              <span v-if="scoped.row.type_name == null" style="color: red"
                >暂无数据</span
              >
              <span v-else>{{ scoped.row.type_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="适用设备型号"
          prop="model_name"
          :show-overflow-tooltip="tooltip"
          min-width="150"
          align="center"
        >
          <template slot-scope="scoped">
            <div>
              <span v-if="scoped.row.model_name == null" style="color: red"
                >暂无数据</span
              >
              <span v-else>{{ scoped.row.model_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="添加人"
          min-width="150"
          prop="realName"
          :show-overflow-tooltip="tooltip"
          align="center"
        >
          <template slot-scope="scoped">
            <div>
              <span v-if="scoped.row.realName == null" style="color: red"
                >暂无数据</span
              >
              <span v-else>{{ scoped.row.realName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="添加时间"
          prop="add_time"
          width="180"
          align="center"
          :show-overflow-tooltip="tooltip"
          sortable
        >
          <template slot-scope="scoped">
            <div>
              <span v-if="scoped.row.add_time == null" style="color: red"
                >暂无数据</span
              >
              <span v-else>{{ scoped.row.add_time }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          prop="operation"
          width="200"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="success"
              plain
              size="small"
              @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确定删除该条数据？"
              @onConfirm="del(scope.row)"
            >
              <el-button
                type="danger"
                plain
                size="small"
                slot="reference"
                style="margin-left: 10px"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <el-drawer
      @close="resetForm('ruleForm')"
      :title="type === 'add' ? '添加温控器版本号' : '编辑温控器版本号'"
      size="480px"
      custom-class="custom-drawer"
      :visible.sync="visible"
    >
      <el-form
        size="small"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="130px"
        class="el-drawer-ruleForm"
      >
        <!-- <el-form-item label="公司名称:" prop="companyId">
          <el-select
            v-model="ruleForm.companyId"
            clearable
            placeholder="请选择公司名称"
            @change="handlercompanyId"
          >
            <el-option
              v-for="item in companySelList"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="温控器版本号" prop="version">
          <el-input
            class="formItem"
            v-model="ruleForm.version"
            placeholder="请输入温控器版本号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="适用设备类型" prop="deviceTypeId">
          <el-select
            class="formItem"
            v-model="ruleForm.deviceTypeId"
            placeholder="请选择适用设备类型"
            filterable
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用设备型号" prop="unit">
          <el-select
            class="formItem"
            v-model="ruleForm.unit"
            placeholder="请选择适用设备型号"
            filterable
            clearable
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="升级包(可多选)" prop="type">
          <el-select
            class="formItem"
            v-model="ruleForm.type"
            placeholder="请选择版本号"
            filterable
            clearable
            multiple
            @change="selectOne(ruleForm.type)"
          >
            <el-option
              v-for="item in versionTypeList"
              :key="item.type"
              :label="item.name"
              :value="item.type"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="上传bin1">
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="action"
            accept=".bin"
            :multiple="true"
            :limit="1"
            :on-success="handlerSuccess"
            :on-remove="handlerRemove"
            :before-upload="hanglerBefore1"
            :data="fileData1"
          >
            <el-button size="small" type="primary">点击上传bin1</el-button>

            <div slot="tip" class="el-upload__tip">
              建议上传.bin文件，且不超过1M
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="上传bin2">
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="action"
            accept=".bin"
            :multiple="true"
            :limit="1"
            :on-success="handlerSuccess1"
            :on-remove="handlerRemove1"
            :before-upload="hanglerBefore2"
            :data="fileData2"
          >
            <el-button size="small" type="primary">点击上传bin2</el-button>

            <div slot="tip" class="el-upload__tip">
              建议上传.bin文件，且不超过1M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="el-drawer__footer">
        <el-button
          type="primary"
          @click.prevent="submitForm('ruleForm')"
          :loading="confirmLoading"
          >{{ confirmLoading ? "保 存 中..." : "保 存" }}</el-button
        >
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  deviceVersionList,
  getVersionList,
  devicTypeList,
  devicModelList,
  deviceVersionAdd,
  deviceVersionEdit,
  deviceTypeDelete,
  companySel,
  picAdd
} from "../../utils/api";
import { mapState, mapGetters } from "vuex";
//温控器版本
export default {
  name: "ThermostatVersions",
  props: ["height"],
  data() {
    return {
      action: "https://devicedata.wadd.vip/api/v1.Version/picAdd",
      formInline: {
        type: "", //设备类型
        version: "", //温控器版本
        unit: "" //设备型号
      },
      versionList: [], //温控器版本列表
      typeList: [], //设备类型列表
      unitList: [], //设备型号列表
      tableData: [], //表格数据
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //总条数
      currentPage: 1, //当前页
      pageSize: 10, //每页条数
      tooltip: true,
      visible: false,
      confirmLoading: false, //按钮加载
      type: "add",
      ruleForm: {
        companyId: "", //公司id
        deviceTypeId: "", //适用设备类型
        unit: "", //适用设备型号
        version: "", //温控器版本号
        file: [], //图片 .bin
        type: "", //userbin1 是2 usebin2 是2
        filePath: ""
      },
      rules: {
        version: [
          { required: true, message: "请输入温控器版本号", trigger: "change" }
        ],
        companyId: [
          { required: true, message: "请选择公司", trigger: "change" }
        ],
        unit: [
          { required: true, message: "请选择适用设备型号", trigger: "change" }
        ],
        type: [{ required: true, message: "请选择bin", trigger: "change" }],
        deviceTypeId: [
          { required: true, message: "请选择适用设备类型", trigger: "change" }
        ]
      },
      userInfo: {}, //用户信息
      currentRow: {}, //当前行信息
      versionTypeList: [
        {
          type: 1,
          name: "user1.bin"
        },
        {
          type: 2,
          name: "user2.bin"
        }
      ],
      // 公司的列表
      companySelList: [],
      //上传bin 的数组
      uploadBIn: [],
      fileData1: {
        version: ""
      },
      fileData2: {
        version: ""
      }
    };
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.getDataInit();
  },
  methods: {
    // 上传bin1前触发的函数
    hanglerBefore1(file) {
      if (this.ruleForm.version == "") {
        this.$message.error("请删除上传的文件,输入版本号 从新上传");
        this.$refs.upload.clearFiles();
      } else {
        this.fileData1.version = this.ruleForm.version;
      }
    },
    // 上传bin2前触发的函数
    hanglerBefore2(file) {
      if (this.ruleForm.version == "") {
        this.$message.error("请删除上传的文件,输入版本号 从新上传");
        this.$refs.upload.clearFiles();
      } else {
        this.fileData2.version = this.ruleForm.version;
      }
    },
    // 上传成功bin1
    handlerSuccess(val) {
      this.ruleForm.type = val.data;
      console.log(this.ruleForm.version + 11);
    },
    // 上传成功bin2
    handlerSuccess1(val) {
      this.ruleForm.filePath = val.data;
    },

    // 移除bin1
    handlerRemove(val) {
      if (val.response.code == 200) {
        this.ruleForm.type = "";
      }
    },
    // 移除bin2
    handlerRemove1(val) {
      if (val.response.code == 200) {
        this.ruleForm.filePath = "";
      }
    },
    getDataInit() {
      if (this.org_id === "" || this.org_id === null || !this.org_id) {
      } else {
        this.getInit();
      }
    },
    handleRemove(file) {
      this.ruleForm.file = [];
    },
    // 点击下拉获取数据
    selectOne(val) {
      this.ruleForm.type = val;
    },
    handleAvatarSuccess(res, file) {
      // var first = fileName.lastIndexOf("."); //取到文件名开始到最后一个点的长度
      // var namelength = fileName.length; //取到文件名长度
      // var filesuffix = fileName.substring(first + 1, namelength); //截取获得后缀名
      // console.log(filesuffix);
      // const resultarr = [];
      // // 拿到上传文件得文件名
      // var fileName = file.name;
      // // 截取出来文件名字
      // var result = fileName.substring(0, 5);
      // // else if (result == "user1" && result == "user2") {
      // //           console.log("上传了2个");
      // //         }
      // resultarr.push(result);
      // console.log(resultarr);
      // if (res.code === 0) {
      //   if (result == "user1") {
      //     this.ruleForm.filetype = 1;
      //   } else if (result == "user2") {
      //     this.ruleForm.filetype = 2;
      //   }
      // }
    },
    async getInit() {
      await this.getSelect();
      await this.getData();
    },
    //下拉框改变事件
    onChange(value, key) {
      this.formInline[key] = value;
      this.currentPage = 1;
      this.getData();
    },
    //获取搜索下拉列表事件
    async getSelect() {
      this.typeList = await this.postRequest(devicTypeList, {
        companyId: this.org_id
      }).then(res => res.data); //设备类型列表
      this.unitList = await this.postRequest(devicModelList, {
        companyId: this.org_id
      }).then(res => res.data); //设备型号
      this.versionList = await this.postRequest(getVersionList, {
        companyId: this.org_id
      }).then(res => res.data); //温控器版本号
    },
    getData() {
      const params = {
        pageSize: this.pageSize,
        pageNumber: this.currentPage,
        typeId: this.formInline.type, //设备类型
        modelId: this.formInline.unit, //设备型号
        versionId: this.formInline.version, //温控器版本号
        companyId: this.org_id
      };
      this.postRequest(deviceVersionList, params).then(res => {
        if (res.code === 200) {
          this.total = res.data.count;
          this.tableData = res.data.data;
        }
      });
    },
    //分页
    handleSizeChange(val) {
      //每页条数
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前第几页
      this.currentPage = val;
      this.getData();
    },
    //添加设备型号
    add() {
      this.visible = true;
      this.type = "add";
    },
    //编辑设备型号
    edit(row) {
      this.currentRow = row;
      this.type = "edit";
      this.visible = true;
      this.ruleForm = {
        deviceTypeId: row.deviceTypeId, //适用设备类型
        unit: row.deviceModelId, //适用设备型号
        version: row.versionNumber, //温控器版本号

        file: [] //图片  txt, .c ,.cpp , .cs
      };
    },
    //删除设备型号
    del(row) {
      const params = {
        user_id: this.userInfo.id,
        versionId: row.id,
        versionNumber: row.versionNumber
      };
      this.postRequest(deviceTypeDelete, params).then(res => {
        if (res.code === 200) {
          this.getInit();
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.type === "edit") {
            if (this.ruleForm.type === undefined) {
              this.ruleForm.type = "";
            }
            if (this.ruleForm.filePath === undefined) {
              this.ruleForm.filePath = "";
            }
          }
          const params = {
            companyId: this.org_id,
            user_id: this.userInfo.id,
            versionNumber: this.ruleForm.version, //温控器版本号
            deviceModelId: this.ruleForm.unit, //适用设备型号
            deviceTypeId: this.ruleForm.deviceTypeId, //适用设备类型
            type: this.ruleForm.type,
            filePath: this.ruleForm.filePath
          };
          const url =
            this.type === "add" ? deviceVersionAdd : deviceVersionEdit;
          if (this.type === "edit") params.id = this.currentRow.id;
          this.confirmLoading = true;
          this.postRequest(url, params)
            .then(res => {
              this.confirmLoading = false;
              if (res.code === 200) {
                this.$message.success(res.msg);
                this.resetForm(formName);
                this.getInit();
              }
            })
            .catch(err => {
              this.confirmLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.visible = false;
      this.ruleForm = {
        type: "", //适用设备类型
        unit: "", //适用设备型号
        version: "", //温控器版本号
        filePath: "",
        file: [] //图片  txt, .c ,.cpp , .cs
      };
      this.$refs.upload.clearFiles();
    }
    // 获取公司的无分页列表
    // getcompanySel() {
    //   this.postRequest(companySel).then(res => {
    //     if (res.code == 200) {
    //       this.companySelList = res.data;
    //     }
    //   });
    // },
    //  拿到公司的id
    // handlercompanyId(val) {
    //   this.ruleForm.companyId = val;
    // }
  },
  computed: {
    ...mapState(["org_id"])
  },
  watch: {
    org_id(val) {
      this.currentPage = 1;
      this.getInit();
    }
  }
};
</script>

<style scoped>
.formItem {
  width: 100%;
}

.header >>> .el-form-item {
  margin-bottom: 0;
}

.header {
  padding: 20px 30px;
  border: 1px solid #eaedf3;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 97%;
  margin: 0 auto;
}

.content {
  padding: 30px;
  box-sizing: border-box;
}

.table {
  margin-top: 30px;
}
</style>
